package project.dade.cn.bst.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.squareup.okhttp.Request;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.InjectView;
import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemClickListener;
import project.dade.cn.bst.R;
import project.dade.cn.bst.adapter.base.RecyclerViewAdapter;
import project.dade.cn.bst.base.ZJPBaseBarActivity;
import project.dade.cn.bst.manager.ApiConfig;
import project.dade.cn.bst.manager.AppApplication;
import project.dade.cn.bst.model.BaseRequestsModel;
import project.dade.cn.bst.model.MyaddressDate;
import project.dade.cn.bst.network.FormatRequest;
import project.dade.cn.bst.network.callback.ResultCallback;
import project.dade.cn.bst.network.request.OkHttpRequest;
import project.dade.cn.bst.utils.AppUtil;
import project.dade.cn.bst.utils.Divider;
import project.dade.cn.bst.utils.LogUtil;
import project.dade.cn.bst.utils.NetRequestUtil;
import project.dade.cn.bst.utils.ToastUtil;
import project.dade.cn.bst.views.EmptyLayout;


public class MyaddressActivity extends ZJPBaseBarActivity implements View.OnClickListener, BGAOnRVItemClickListener ,BGAOnItemChildClickListener {

    @InjectView(R.id.universal_toolBar)
    TextView add;
    @InjectView(R.id.baseListView)
    RecyclerView recyclerView;
    private RecyclerViewAdapter addressAdapter;
    @InjectView(R.id.error_layout)
    EmptyLayout mErrorLayout;
    private String  mark ;
    public static int REQUEST_CODE = 1200;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activitty_myaddress);
        add.setOnClickListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        addressAdapter = new RecyclerViewAdapter( recyclerView);
        addressAdapter.setOnRVItemClickListener(this);
        recyclerView.addItemDecoration(new Divider(this));
        recyclerView.setAdapter(addressAdapter);
        addressAdapter.setOnRVItemClickListener(this);
        addressAdapter.setOnItemChildClickListener(this);
        mark=getIntent().getStringExtra("mark");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.universal_toolBar:
                if(mark.equals("1")){
                    Intent mIntentRegInfo = new Intent(this, AddaddressActivity.class);
                    mIntentRegInfo.putExtra("edit","0");
                     mIntentRegInfo.putExtra("mark", mark);
                    startActivity(mIntentRegInfo);
                    finish();
                }
                else {
                    Intent mIntentRegInfo = new Intent(this, AddaddressActivity.class);
                    mIntentRegInfo.putExtra("edit", "0");
                    startActivity(mIntentRegInfo);
                    finish();
                }

        }

    }


    @Override
    protected void onResume() {
        super.onResume();
        initRequest();

    }

    private void initRequest() {
        if (AppUtil.isNetworkAvailable(this)) {
            requestGetAddress();
        } else {
            mErrorLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
        }

    }
    private void requestGetAddress() {
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("UID", AppApplication.getInstance().getSpUtil().getUserID().toString());
        hashMap.put("MobilePhone", AppApplication.getInstance().getSpUtil().getUSER_mobile());
        Map<String, String> params = new HashMap<String, String>();
        params.put("UID", AppApplication.getInstance().getSpUtil().getUserID().toString());
        params.put("MobilePhone", AppApplication.getInstance().getSpUtil().getUSER_mobile());
        params.put("Sign", FormatRequest.main(hashMap));
        new OkHttpRequest.Builder()
                .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.Ress).params(params)
                .post(new ResultCallback<String>() {
                    @Override
                    public void onError(Request request, Exception e) {

                        ToastUtil.showShort(MyaddressActivity.this, "网络相应失败请稍后再试");
                    }

                    @Override
                    public void onResponse(String response) {
                        LogUtil.i(TAG, "提交收获地址：" + response);
                        if (TextUtils.isEmpty(NetRequestUtil.requestsError(response, "获取收货地址"))) {
                            BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);
                            LogUtil.i(TAG, "提交收获地址1：" + model.getData());
                            if (model != null && model.getResult() == 0) {

                                //获取请求成功
                                List<MyaddressDate> myaddressDates = new ArrayList<>();
                                myaddressDates = JSON.parseArray(model.getData(), MyaddressDate.class);
                                if (myaddressDates.size() == 0) {
                                    mErrorLayout.setErrorType(EmptyLayout.NODATA);
                                    mErrorLayout.setErrorMessage("暂无收货地址");

                                } else {
                                    int position = -1;
                                    for (int i = 0; i < myaddressDates.size(); i++) {
                                        if (myaddressDates.get(i).getStat().equals("1")) {
                                            position = i;

                                        }
                                    }
                                    if (position != -1) {
                                        MyaddressDate test = myaddressDates.get(position);
                                        myaddressDates.remove(position);
                                        myaddressDates.add(0, test);

                                    } else {

                                    }
                                    LogUtil.i(TAG, "获取的地址：" + myaddressDates);
                                    addressAdapter.setDatas(myaddressDates);
                                }

                            }

                        } else {
                            ToastUtil.showShort(MyaddressActivity.this, NetRequestUtil.requestsError(response, "获取收获地址"));

                        }
                    }

                });
    }

    @Override
    public void onRVItemClick(ViewGroup viewGroup, View childView, int position) {
        if(mark.equals("3")){
            Intent mIntentRegInfo = new Intent(MyaddressActivity.this, AddaddressActivity.class);
            mIntentRegInfo.putExtra("name", addressAdapter.getItem(position).getUsername());
            mIntentRegInfo.putExtra("address",addressAdapter.getItem(position).getAddress());
            mIntentRegInfo.putExtra("id",addressAdapter.getItem(position).getId());
            mIntentRegInfo.putExtra("phone",addressAdapter.getItem(position).getPhone());
            mIntentRegInfo.putExtra("edit","1");
            startActivity(mIntentRegInfo);
            finish();
        }else {
            Intent mIntent = new Intent();
            Bundle mBundle = new Bundle();
            mBundle.putString("name", addressAdapter.getItem(position).getUsername());
            mBundle.putString("address",addressAdapter.getItem(position).getAddress());
            mBundle.putString("id",addressAdapter.getItem(position).getId());
            mBundle.putString("phone", addressAdapter.getItem(position).getPhone());
            mIntent.putExtra("tempAddress", mBundle);
            MyaddressActivity.this.setResult(SubmitOrder.REQUEST_CODE, mIntent);
            finish();

        }

    }

    @Override
    public void onItemChildClick(ViewGroup viewGroup, View childView, final int position) {
        if (childView.getId() == R.id.tv_item_bgaswipe_delete) {
            if (AppUtil.isNetworkAvailable(MyaddressActivity.this)) {
                HashMap<String, String> hashMap = new HashMap<String, String>();
                hashMap.put("UID", AppApplication.getInstance().getSpUtil().getUserID().toString());
                hashMap.put("MobilePhone", AppApplication.getInstance().getSpUtil().getUSER_mobile());
                hashMap.put("Id", addressAdapter.getItem(position).getId().toString());
                hashMap.put("Flag", "1");
                Map<String, String> params = new HashMap<String, String>();
                params.put("UID", AppApplication.getInstance().getSpUtil().getUserID().toString());
                params.put("MobilePhone", AppApplication.getInstance().getSpUtil().getUSER_mobile());
                params.put("Id", addressAdapter.getItem(position).getId().toString());
                params.put("Flag", "1");
                params.put("Sign", FormatRequest.main(hashMap));
                new OkHttpRequest.Builder()
                        .url(ApiConfig.getHostAddress() + ApiConfig.SERVER_URL.Address).params(params)
                        .post(new ResultCallback<String>() {
                            @Override
                            public void onError(Request request, Exception e) {

                                ToastUtil.showShort(MyaddressActivity.this, "网络相应失败请稍后再试");
                            }
                            @Override
                            public void onResponse(String response) {
                                LogUtil.i(TAG, "删除收获地址：" + response);
                                if (TextUtils.isEmpty(NetRequestUtil.requestsError(response, "删除收货地址"))) {
                                    BaseRequestsModel model = JSON.parseObject(response, BaseRequestsModel.class);
                                    if (model != null && model.getResult() == 0) {
                                        addressAdapter.closeOpenedSwipeItemLayoutWithAnim();
                                        addressAdapter.removeItem(position);
                                        if(addressAdapter.getDatas().size()==0){
                                            mErrorLayout.setErrorType(EmptyLayout.NODATA);
                                            mErrorLayout.setErrorMessage("暂无收货地址");
                                        }
                                    }

                                } else {
                                    ToastUtil.showShort(MyaddressActivity.this, NetRequestUtil.requestsError(response, "删除收获地址"));
                                }
                            }

                        });

            } else {
                ToastUtil.showShort(MyaddressActivity.this, R.string.tips_network_error);
            }

        }
    }

    /**
     * 跳转相关页功能
     *
     * @param <T>
     */
    private <T> void redirectToPage(Class<T> class1) {

        startActivity(new Intent(this, class1));

    }
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            this.finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}
